<template>
    <!-- <a-drawer width="35%" :label-col="4" :wrapper-col="14" :visible="open" @close="onClose"> -->
    <!-- <a-divider orientation="left">
        <b>{{ formTitle }}</b>
      </a-divider> -->
    <div class="form-wrap">
        <div class="title">专车发货</div>
        <a-form-model ref="form" :model="form" :rules="rules">
            <a-form-model-item label="项目名称" prop="projectName">
                <a-input v-model="form.projectName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="项目经理" prop="projectManager">
                <a-select placeholder="请选择项目经理" :default-active-first-option="false" :show-arrow="false"
                    :filter-option="false" show-search :not-found-content="null" v-model="form.projectManager"
                    @search="handleChange">
                    <a-select-option v-for="(d, index) in projectManagerOptions" :key="index" :value="d.userid">{{
                        d.name + '(' + d.mobile + ')'
                        }}</a-select-option>
                </a-select>
            </a-form-model-item>
            <a-form-model-item label="设备类型" prop="eqType">
                <a-select placeholder="请选择设备类型" v-model="form.eqType">
                    <a-select-option v-for="(d, index) in dict.type['eq_type']" :key="index" :value="d.value">{{ d.label
                        }}</a-select-option>
                </a-select>
            </a-form-model-item>
            <a-table v-if="form.eqType == 2" bordered :data-source="dataSourceType" :columns="columnsType" rowKey="key"
                :pagination="false" :custom-row='(record) => {
                    return {
                        on: { // 事件
                            click: () => editType(record),       // 点击行
                        },
                    }
                }'>
                <template slot="operation" slot-scope="text, record">
                    <a href="javascript:;" @click.stop="onDeleteType(record)">删除</a>
                </template>
            </a-table>
            <a-button v-if="form.eqType == 2" type="primary" class="editable-add-btn" @click="handleAddTableType">
                添加表格行
            </a-button>
            <a-form-model-item label="发货方式" prop="deliverWay">
                <a-select placeholder="请选择发货方式" v-model="form.deliverWay">
                    <a-select-option v-for="(d, index) in dict.type['deliver_way']" :key="index" :value="d.value">{{
                        d.label
                    }}</a-select-option>
                </a-select>
            </a-form-model-item>
            <a-form-model-item label="发货明细链接" prop="dingtalkImgLinks">
                <a-textarea v-model="form.dingtalkImgLinks" autoSize style="width:100%" placeholder="请输入" />
                <btn-upload v-model="form.dingtalkImgLinks"></btn-upload>
            </a-form-model-item>
            <a-form-model-item label="发货名称" prop="deliverName">
                <a-textarea v-model="form.deliverName" style="width: 100%;" auto-size placeholder="请输入发货名称" />
            </a-form-model-item>
            <a-form-model-item label="发货原因" prop="deliverDesc">
                <a-textarea v-model="form.deliverDesc" style="width: 100%;" placeholder="请选择" />
            </a-form-model-item>
            <a-table bordered :data-source="dataSource" :columns="columns" rowKey="key" :pagination="false" :custom-row='(record) => {
                return {
                    on: { // 事件
                        click: () => edit(record),       // 点击行
                    },
                }
            }'>
                <template slot="operation" slot-scope="text, record">
                    <a href="javascript:;" @click.stop="onDelete(record)">删除</a>
                </template>
            </a-table>
            <a-button type="primary" class="editable-add-btn" @click="handleAddTable">
                添加表格行
            </a-button>
            <a-form-model-item label="目的地" prop="endAddrList">
                <a-cascader v-model="form.endAddrList" :options="addressList" :field-names="{
                    label: 'city',
                    value: 'city',
                    children: 'children',
                }" placeholder="请选择目的地" />
            </a-form-model-item>
            <a-form-model-item label="详细地址及联系人" prop="endContact">
                <a-textarea v-model="form.endContact" style="width:100%" placeholder="请选择" />
            </a-form-model-item>
            <a-form-model-item label="装车人员" prop="puckVehPeople">
                <!-- <a-input v-model="form.puckVehPeople" placeholder="请输入" style="width:100%" /> -->
                <a-select placeholder="请选择项目经理" :default-active-first-option="false" :show-arrow="false"
                    :filter-option="false" show-search :not-found-content="null" v-model="form.puckVehPeople"
                    @search="handleChange">
                    <a-select-option v-for="(d, index) in projectManagerOptions" :key="index" :value="d.userid">{{
                        d.name + '(' + d.mobile + ')'
                        }}</a-select-option>
                </a-select>
            </a-form-model-item>
            <a-form-model-item label="需求车型" prop="needVehicle">
                <a-input v-model="form.needVehicle" placeholder="请输入" style="width:100%" />
            </a-form-model-item>
            <a-form-model-item label="发货日期" prop="deliverDate">
                <a-date-picker v-model="form.deliverDate" allowClear show-time format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择" @change="(dirname, data) => handleTime(data, 'deliverDate', dirname)" />
            </a-form-model-item>
            <a-form-model-item label="预计到货日期" prop="needGiveDate">
                <a-date-picker v-model="form.needGiveDate" allowClear :disabled-date="disabledDate"
                    :disabled="!form.deliverDate" format="YYYY-MM-DD HH:mm:ss" show-time placeholder="请选择"
                    @change="(__dirname, data) => handleTime(data, 'needGiveDate')" />
            </a-form-model-item>
            <a-form-model-item label="发货设备入库单号" prop="pushStashNo">
                <a-input v-model="form.pushStashNo" style="width:100%" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="发货设备移库单号" prop="changeStashNo">
                <a-input v-model="form.changeStashNo" style="width:100%" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="预估装载率" prop="estimateLoadRate">
                <a-input-number v-model="form.estimateLoadRate" :max="100" style="width:100%" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="公里数" prop="kilometre">
                <a-input-number v-model="form.kilometre" style="width:100%" placeholder="请输入" />
            </a-form-model-item>
            <!-- <a-form-model-item v-show="form.eqType !== '0'" label="图片" prop="dingtalkImgLinks">
                <base-upload v-model="form.dingtalkImgLinks"></base-upload>
            </a-form-model-item> -->
            <!-- <a-form-model-item v-show="form.eqType === '0'" label="链接" prop="dingtalkImgLinks">
                <a-input v-model="form.dingtalkImgLinks" style="width:100%" placeholder="请输入" />
            </a-form-model-item> -->
            <div class="btn-wrap">
                <a-button type="primary" class="btn" :loading="submitLoading" @click="submitForm">
                    发起
                </a-button>
            </div>
        </a-form-model>
        <editable-cell ref="editTable" :text="record" @edit="handleEdit" @add="onCellChange" />
        <editable-cell-type ref="editTableType" :text="recordType" @edit="handleEditType" @add="onCellChangeType" />
    </div>
    <!-- </a-drawer> -->
</template>

<script>
import EditableCell from './editTble.vue';
import EditableCellType from './editTbleType.vue';
import baseUpload from '@/components/imgUpload'
import { handleInitiate, getDingUserList, materialAddList } from "@/api/demo";
import addressList from "@/utils/ChinaCitys.js";
import { Cascader as ACascader } from 'ant-design-vue'
import BtnUpload from '@/components/BtnUpload'
export default {
    name: 'CreateForm',
    props: {
    },
    components: {
        baseUpload,
        'a-cascader': ACascader, // 局部注册组件
        EditableCell,
        EditableCellType,
        BtnUpload
    },
    dicts: ['deliver_way', 'eq_type'],
    data() {
        return {
            submitLoading: false,
            formTitle: '',
            // 表单参数
            form: {
                projectName: undefined,
                eqType: undefined,
                projectManager: undefined,
                deliverWay: undefined,
                deliverDesc: undefined,
                deliverName: undefined,
                endAddrList: undefined,
                endContact: undefined,
                puckVehPeople: undefined,
                deliverDate: undefined,
                needGiveDate: undefined,
                needVehicle: undefined,
                estimateLoadRate: undefined,
                pushStashNo: undefined,
                changeStashNo: undefined,
                kilometre: undefined,
                dingtalkImgLinks: undefined,
                isAbnormalSum: false,
            },
            open: false,
            rules: {
                projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
                eqType: [{ required: true, message: '设备类型不能为空', trigger: 'blur' }],
                projectManager: [{ required: true, message: '项目经理不能为空', trigger: 'blur' }],
                deliverWay: [{ required: true, message: '发货方式不能为空', trigger: 'blur' }],
                deliverDesc: [{ required: true, message: '发货原因不能为空', trigger: 'blur' }],
                deliverName: [{ required: true, message: '发货名称不能为空', trigger: 'blur' }],
                endAddrList: [{ required: true, message: '目的地不能为空', trigger: 'blur' }],
                puckVehPeople: [{ required: true, message: '装车人员不能为空', trigger: 'blur' }],
                deliverDate: [{ required: true, message: '发货日期不能为空', trigger: 'change' }],
                needGiveDate: [{ required: true, message: '需求到货日期不能为空', trigger: 'change' }],
                needVehicle: [{ required: true, message: '需求车型不能为空', trigger: 'blur' }],
                estimateLoadRate: [{ required: true, message: '预估装载率不能为空', trigger: 'blur' }],
                pushStashNo: [{ required: true, message: '发货设备入库单号不能为空', trigger: 'blur' }],
                changeStashNo: [{ required: true, message: '发货设备移库单号不能为空', trigger: 'blur' }],
                kilometre: [{ required: true, message: '公里数不能为空', trigger: 'blur' }],
                dingtalkImgLinks: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
            },
            projectManagerOptions: [],
            addressList: undefined,
            columns: [
                {
                    title: '始发地',
                    dataIndex: 'address',
                },
                {
                    title: '详细地址及联系人',
                    dataIndex: 'info',
                },
                {
                    title: '操作',
                    dataIndex: 'operation',
                    scopedSlots: { customRender: 'operation' },
                },
            ],
            columnsType: [
                {
                    title: '品名',
                    dataIndex: 'device',
                },
                {
                    title: '规格',
                    dataIndex: 'size',
                },
                {
                    title: '数量',
                    dataIndex: 'count',
                },
                {
                    title: '操作',
                    dataIndex: 'operation',
                    scopedSlots: { customRender: 'operation' },
                },
            ],
            visibleDrawer: false,
            dataSource: [
            ],
            dataSourceType: [
            ],
            countType: 0,
            count: 0,
            record: {},
            recordType: {},
            status: false,
            statusType: false,
        }
    },
    filters: {
    },
    created() {
        this.addressList = addressList
        getDingUserList({ mobile: '' }).then((res) => {
            this.projectManagerOptions = res.data
        })
    },
    computed: {
    },
    watch: {
    },
    methods: {
        disabledDate(endValue) {
            const startValue = this.form.dirname;
            if (!endValue || !startValue) {
                return false;
            }
            return startValue.valueOf() >= endValue.valueOf();
        },
        handleEdit(value) {
            const dataSource = [...this.dataSource];
            this.dataSource = dataSource.map((item) => {
                if (item.key === this.record.key) {
                    value.info = value.detailAdress + ' ' + value.name + ' ' + value.phone
                    value.key = item.key
                    return value
                } else {
                    return item
                }
            })
        },
        handleEditType(value) {
            const dataSource = [...this.dataSourceType];
            this.dataSourceType = dataSource.map((item) => {
                if (item.key === this.recordType.key) {
                    value.key = item.key
                    return value
                } else {
                    return item
                }
            })
        },
        onDelete(record) {
            const that = this
            this.$confirm({
                title: '确认删除所选中数据?',
                content: '当前选中设备为' + record.device + '的数据',
                onOk() {
                    const dataSource = [...that.dataSource];
                    that.dataSource = dataSource.filter(item => item.key !== record.key);
                },
                onCancel() { }
            })
        },
        onDeleteType(record) {
            const that = this
            this.$confirm({
                title: '确认删除所选中数据?',
                content: '当前选中设备为' + record.device + '的数据',
                onOk() {
                    const dataSource = [...that.dataSourceType];
                    that.dataSourceType = dataSource.filter(item => item.key !== record.key);
                },
                onCancel() { }
            })
        },
        handleAddTable() {
            if (!this.status) {
                this.$refs.editTable.open(1)
            }
        },
        handleAddTableType() {
            if (!this.statusType) {
                this.$refs.editTableType.open(1)
            }
        },
        edit(record) {
            this.record = record
            if (!this.status) {
                this.$refs.editTable.open(2)
            }

        },
        editType(record) {
            this.recordType = record
            if (!this.statusType) {
                this.$refs.editTableType.open(2)
            }

        },
        onCellChange(value) {
            const { count, dataSource } = this;
            let newData = value;
            newData.key = count
            newData.info = value.detailAdress + ' ' + value.name + ' ' + value.phone
            this.dataSource = [...dataSource, newData];
            this.count = count + 1;
        },
        onCellChangeType(value) {
            const { countType, dataSourceType } = this;
            let newData = value;
            newData.key = countType
            this.dataSourceType = [...dataSourceType, newData];
            this.countType = countType + 1;
        },
        onClose() {
            this.open = false
            this.iconVisible = false
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.iconVisible = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                projectName: undefined,
                eqType: undefined,
                projectManager: undefined,
                deliverWay: undefined,
                deliverDesc: undefined,
                deliverName: undefined,
                endAddrList: undefined,
                endContact: undefined,
                puckVehPeople: undefined,
                deliverDate: undefined,
                needGiveDate: undefined,
                needVehicle: undefined,
                estimateLoadRate: undefined,
                pushStashNo: undefined,
                changeStashNo: undefined,
                kilometre: undefined,
                dingtalkImgLinks: undefined,
                isAbnormalSum: false,
            }
            this.$refs.form?.clearValidate()
        },
        handleChange(value) {
            getDingUserList({ mobile: value }).then((res) => {
                this.projectManagerOptions = res.data
            })
        },
        /** 新增按钮操作 */
        handleAdd(row) {
            this.reset()
            this.open = true
            this.formTitle = '发起流程'
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            this.$emit('select-tree')
            getMenu(row.menuId).then(response => {
                this.form = response.data
                this.open = true
                this.formTitle = '修改菜单'
            })
        },
        handleTime(data, name, dirname) {
            this.form[name] = data
            if (dirname) {
                this.form.dirname = dirname
            }

        },
        handelvisibleChange(val) {
            this.status = val
        },
        handelvisibleChangeType(val) {
            this.statusType = val
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs.form.validate(valid => {
                if (valid) {
                    // this.submitLoading = true
                    this.form.endAddr = this.form.endAddrList.join()
                    this.form.beginAddr = this.dataSource.map((item) => {
                        if (item.address) {
                            // res[item.address] = item.phone
                            let res = item.address + '/' + item.info
                            return res
                        }
                    })
                    this.form.beginAddr = this.form.beginAddr.filter(item => item !== undefined)
                    if (this.form.eqType == 2) {
                        this.form.materialList = this.dataSourceType
                    }
                    console.log(this.form);
                    handleInitiate(this.form).then((res) => {
                        if (res.code === 200) {
                            this.$message.success('发起成功')
                            if (this.form.eqType == 2) {
                                const query = {
                                    vehicleId: res.msg,
                                    type: 2,
                                    materialList: this.dataSourceType
                                }
                                materialAddList(query)
                            }
                        }
                    })
                } else {
                    return false
                }
            })
        },
    }
}
</script>
<style lang="less" scoped>
.title {
    height: 45px;
    line-height: 45px;
    text-align: center;
    font-size: 18px;
    font-weight: 600;
}

.form-wrap {
    width: 80%;
    max-width: 750px;
    margin: auto;
    padding-bottom: 10px;
}

.btn-wrap {
    width: 100%;
    display: flex;
    justify-content: center;
}

.editable-add-btn {
    width: 100%;
    max-width: 300px;
    margin: 10px 0;
}
</style>